<template>
    <div class="app-container">
        <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch">
            <el-form-item label="机构名称" prop="organizationName">
                <el-input v-model="queryParams.organizationName" placeholder="请输入机构名称" @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="授权手机号" prop="contactInformation">
                <el-input v-model="queryParams.contactInformation" placeholder="请输入授权手机号" @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item>
                <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
                <el-button icon="Refresh" @click="resetQuery">重置</el-button>
                <el-button type="success" plain icon="Plus" @click="handleAdd"
                    v-hasPermi="['decor:organization:add']">新增</el-button>
            </el-form-item>
        </el-form>
        <el-table v-loading="loading" :data="organizationList" default-expand-all row-key="organizationId"
            :tree-props="{ children: 'updateRecords' }">
            <el-table-column label="机构ID" :show-overflow-tooltip="true" align="center" prop="organizationId" />
            <el-table-column label="机构名称" :show-overflow-tooltip="true" align="center" prop="organizationName">
            </el-table-column>
            <el-table-column label="机构地址" :show-overflow-tooltip="true" align="center" prop="address">
            </el-table-column>
            <el-table-column label="授权手机号" :show-overflow-tooltip="true" align="center" prop="contactInformation">
            </el-table-column>
            <el-table-column label="机构logo" width="90" :show-overflow-tooltip="true" align="center" prop="avatarImg">
                <template #default="scope">
                    <image-preview :width="60" :height="60" :src="scope.row.avatarImg"
                        :preview-src-list="[scope.row.avatarImg]"></image-preview>
                </template>
            </el-table-column>
            <el-table-column label="机构形象照" width="90" :show-overflow-tooltip="true" align="center" prop="figureImg">
                <template #default="scope">
                    <image-preview :width="60" :height="60" :src="scope.row.figureImg"
                        :preview-src-list="[scope.row.figureImg]"></image-preview>
                </template>
            </el-table-column>
            <el-table-column label="成立时间" :show-overflow-tooltip="true" align="center" prop="foundingYears">
                <template #default="scope">
                    <span>{{ parseTime(scope.row.foundingYears, "{y}-{m}-{d}") }}</span>
                </template>
            </el-table-column>
            <el-table-column label="旗下设计师(名)" :show-overflow-tooltip="true" align="center" prop="designerIds">
                <template #default="scope">
                    <span>{{ scope.row.designerNum }}</span>
                </template>
            </el-table-column>
            <el-table-column label="机构状态" :show-overflow-tooltip="true" width="80" align="center" prop="organizationStatus">
                <template #default="scope">
                    <dict-tag :options="organization_status" :value="scope.row.organizationStatus" />
                </template>
            </el-table-column>
            <el-table-column label="排序" :show-overflow-tooltip="true" align="center" prop="sort1">
                <template #default="scope">
                    <div>{{ scope.row.sort1 }}</div>
                    <el-button link type="warning" size="small" @click="editSort(scope.row)"
                        v-hasPermi="['decor:designer:edit']">修改排序</el-button>
                </template>
            </el-table-column>
            <el-table-column label="操作" align="center">
                <template #default="scope">
                    <el-button link type="primary" size="small" icon="Edit" @click="handleUpdate(scope.row)"
                        v-hasPermi="['decor:organization:edit']">修改</el-button>
                    <el-button link type="warning" size="small" icon="Delete" @click="handleDelete(scope.row)"
                        v-hasPermi="['decor:organization:remove']">删除</el-button>
                    <el-button link type="primary"
                        v-show="scope.row.organizationStatus === 1 || scope.row.organizationStatus === 3"
                        :icon="scope.row.organizationStatus === 3 ? 'Upload' : 'Download'" size="small"
                        @click="handleDownload(scope.row)" v-hasPermi="['decor:organization:edit']">{{
                            scope.row.organizationStatus === 3 ?
                            '上架' : '下架' }}</el-button>
                </template>
            </el-table-column>
        </el-table>

        <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
            v-model:limit="queryParams.pageSize" @pagination="getList" />

    </div>
</template>

<script setup>
import { listOrganization, delOrganization, updateOrganization } from "@/api/decor/designAgency";
import { getImgUrl } from "@/api/decor/designer";
const { proxy } = getCurrentInstance();
const router = useRouter();
const { organization_status } = proxy.useDict('organization_status');
// 表格数据
const organizationList = ref([]);
// 遮罩层
const loading = ref(true);
// 显示搜索条件
const showSearch = ref(true);
// 总条数
const total = ref(0);

const data = reactive({
    queryParams: {
        pageNum: 1,
        pageSize: 10,
        organizationName: null,
        contactInformation: null,
        // orderByColumn: 'organizationId',
        // isAsc: 'desc'
    },
});

const { queryParams } = toRefs(data);

// 表格数据
function getList() {
    loading.value = true;
    listOrganization(queryParams.value).then(response => {
        let imgUrlPromises = [];
        let data = response.rows.map((v) => {
            return { ...v, figureImg: '', avatarImg: '' }
        })
        data.forEach((v) => {
            // 获取头像的异步操作
            if (v.avatar) {
                let avatarPromise = getImgUrl(v.avatar).then((res) => {
                    v.avatarImg = res.data[0].url;
                });
                imgUrlPromises.push(avatarPromise);
            }
            // 获取形象照的异步操作
            if (v.profilePicture) {
                let coverImagePromise = getImgUrl(v.profilePicture).then((res) => {
                    v.figureImg = res.data[0].url;
                });
                imgUrlPromises.push(coverImagePromise);
            }
            if (v.updateRecords.length > 0) {
                if (v.updateRecords[0].avatar) {
                    let promiseUpdateRecordsAvatar = getImgUrl(v.updateRecords[0].avatar).then((res) => {
                        v.updateRecords[0].avatarImg = res.data[0].url;
                    });
                    imgUrlPromises.push(promiseUpdateRecordsAvatar);
                }
                // 获取形象照的异步操作
                if (v.updateRecords[0].profilePicture) {
                    let coverImagePromise = getImgUrl(v.updateRecords[0].profilePicture).then((res) => {
                        v.updateRecords[0].figureImg = res.data[0].url;
                    });
                    imgUrlPromises.push(coverImagePromise);
                }
            }
        })
        Promise.all(imgUrlPromises).then(() => {
            organizationList.value = data;
            total.value = response.total;
            loading.value = false;
        });

    });
}

// 搜索按钮操作
function handleQuery() {
    queryParams.value.pageNum = 1;
    getList();
}

/** 重置按钮操作 */
function resetQuery() {
    proxy.resetForm("queryRef");
    handleQuery();
}


/** 新增按钮操作 */
function handleAdd() {
    router.push('/designerAgency/editDesignerAgency')
}

/** 修改按钮操作 */
function handleUpdate(row) {
    router.push('/designerAgency/editDesignerAgency/' + row.organizationId)
}
// 调整排序
const editSort = (row) => {
    proxy.$prompt('请输入"' + row.organizationName + '"的排序', "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        closeOnClickModal: false,
        inputPattern: /^(?:[1-9][0-9]{0,3})$/,
        inputErrorMessage: "请输入介于 1 和 9999 之间的数字",
    }).then(({ value }) => {
        const data = {
            ...row,
            sort1: value
        }
        updateOrganization(data).then(response => {
            proxy.$modal.msgSuccess("修改排序成功");
            getList()
        });
    }).catch(() => { });
}

/** 删除按钮操作 */
function handleDelete(row) {
    const _organizationIds = row.organizationId;
    proxy.$modal.confirm('是否确认删除机构名称为"' + row.organizationName + '"的数据？').then(function () {
        return delOrganization(_organizationIds);
    }).then(() => {
        getList();
        proxy.$modal.msgSuccess("删除成功");
    }).catch(() => { });
}
// 下架操作
const handleDownload = (row) => {
    const status = row.organizationStatus === 3 ? '上架' : '下架'
    const organizationStatus = row.organizationStatus === 3 ? 1 : 3
    proxy.$modal.confirm(`是否确认${status}机构"' ${row.organizationName}  '"？`).then(function () {
        return updateOrganization({ ...row, organizationStatus: organizationStatus });
    }).then(() => {
        getList();
        proxy.$modal.msgSuccess(`${status}成功`);
    }).catch(() => { });
}
getList();
</script>